package com.niiwoo.civet.mobile.controller;

import com.alibaba.dubbo.rpc.RpcContext;
import com.alibaba.fastjson.JSON;
import com.niiwoo.civet.account.dto.request.StatisticUserBillAmountRequestDTO;
import com.niiwoo.civet.account.dto.response.StatisticUserBillAmountReponseDTO;
import com.niiwoo.civet.account.enums.BillAmountStatisticsEnum;
import com.niiwoo.civet.account.service.bill.UserBillStatisticsDubboService;
import com.niiwoo.civet.trade.dto.request.InvestAmountStatisticsRequestDTO;
import com.niiwoo.civet.trade.dto.response.InvestAmountStatisticsResponseDTO;
import com.niiwoo.civet.trade.dto.response.creditor.CreditorConfigDTO;
import com.niiwoo.civet.trade.service.creditor.CreditorConfigDubboService;
import com.niiwoo.civet.trade.service.invest.InvestOrderDubboService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Future;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.FastDateFormat;
import org.joda.time.DateTime;
import org.joda.time.Days;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.dubbo.config.annotation.Reference;
import com.niiwoo.civet.account.dto.request.QueryMoneyTotalRequestDTO;
import com.niiwoo.civet.account.dto.response.QueryMoneyTotalResponseDTO;
import com.niiwoo.civet.account.service.MoneyTotalDubboService;
import com.niiwoo.civet.mobile.vo.response.FortunePlazaResponseVO;
import com.niiwoo.civet.user.dto.response.UserBasicInfoResponseDTO;
import com.niiwoo.civet.user.service.UserBasicInfoDubboService;
import com.niiwoo.tripod.web.util.PrincipalContext;
import com.niiwoo.tripod.web.vo.Result;

@RestController
@RequestMapping("/fortunePlaza")
@Api(tags = "财富中心: (廖君君)", description = "/fortunePlaza")
@Slf4j
public class FortunePlazaController {

	@Reference(version = "1.0.0")
	private MoneyTotalDubboService moneyTotalDubboService;
	
	@Reference(version = "1.0.0")
	private UserBasicInfoDubboService userBasicInfoDubboService;

	@Reference(version = "1.0.0")
	private CreditorConfigDubboService creditorConfigDubboService;

	@Reference(version = "1.0.0")
	private InvestOrderDubboService investOrderDubboService;

	@Reference(version = "1.0.0")
	private UserBillStatisticsDubboService userBillStatisticsDubboService;

	@PostMapping("/queryFortunePlaza")
	@ApiOperation("查询财富中心")
	public Result<FortunePlazaResponseVO> queryFortunePlaza() {
		String userId =  PrincipalContext.getUserId();

		InvestAmountStatisticsRequestDTO investAmountStatisticsRequestDTO = new InvestAmountStatisticsRequestDTO();
		investAmountStatisticsRequestDTO.setUserId(userId);
		investAmountStatisticsRequestDTO.setQueryType(Byte.valueOf("0"));
		Future<InvestAmountStatisticsResponseDTO> dueInFuture = RpcContext.getContext().asyncCall(() -> investOrderDubboService.myInvestAmountStatistics(investAmountStatisticsRequestDTO));

		StatisticUserBillAmountRequestDTO statisticUserBillAmountRequestDTO = new StatisticUserBillAmountRequestDTO();
		List<BillAmountStatisticsEnum> billAmountStatisticsEnums = Arrays.asList(
				BillAmountStatisticsEnum.RECEIVED_PAYMENT_INTEREST,
				BillAmountStatisticsEnum.PLATFORM_PRIZE,
				BillAmountStatisticsEnum.CARD_AND_REDPACKET,
				BillAmountStatisticsEnum.RECOMMEND_PRIZE,
				BillAmountStatisticsEnum.ACCUMULATED_PROFIT);
		statisticUserBillAmountRequestDTO.setUserId(userId);
		statisticUserBillAmountRequestDTO.setBillAmountStatisticsEnums(billAmountStatisticsEnums);

		Future<List<StatisticUserBillAmountReponseDTO>> receivedStatisticFuture = RpcContext.getContext().asyncCall(() -> userBillStatisticsDubboService.statisticUserBillAmounts(statisticUserBillAmountRequestDTO));

		QueryMoneyTotalRequestDTO request = new QueryMoneyTotalRequestDTO();
		request.setUserId(userId);
		QueryMoneyTotalResponseDTO response = moneyTotalDubboService.queryMoneyTotal(request);

		FortunePlazaResponseVO responseVO = new FortunePlazaResponseVO();
		BeanUtils.copyProperties(response, responseVO);
		
		UserBasicInfoResponseDTO userBasic = userBasicInfoDubboService.getUserBasicInfo(userId);
		if(userBasic != null && userBasic.getCreateTime() != null){
			responseVO.setRegisterDate(userBasic.getCreateTime());
			DateTime today = new DateTime(FastDateFormat.getInstance("yyyy-MM-dd").format(new Date()));
			responseVO.setRegisterDay(Days.daysBetween(
					new DateTime(FastDateFormat.getInstance("yyyy-MM-dd").format(userBasic.getCreateTime())), today)
					.getDays() + 1);
		}

		// 债转开关
		CreditorConfigDTO notifyDTO = creditorConfigDubboService.getCreditorConfigs();
		if (notifyDTO != null) {
			responseVO.setCreditorSwitch(notifyDTO.getCreditorSwitch());
		}

		try {
			InvestAmountStatisticsResponseDTO dueIn = dueInFuture.get();
			responseVO.setDueInCorpus(dueIn.getDueInCorpus());
			responseVO.setReferenceInterest(dueIn.getReferenceInterest());
			responseVO.setDueInCorpusInterest(dueIn.getDueInCorpusInterest());

			// 财富总额(可用余额[投资账户余额+借款账户余额]+在途资金 + 待收本息)
			responseVO.setAmountTotal(responseVO.getInvestorAvailableBalance().add(responseVO.getBorrowerAvailableBalance())
					.add(responseVO.getOnWayAmount()).add(responseVO.getDueInCorpusInterest()));
		} catch (Exception e) {
			log.error("远程调用服务失败InterruptedException:", e);
		}

		BigDecimal investIncome = BigDecimal.ZERO;
		BigDecimal prize = BigDecimal.ZERO;
		BigDecimal platformGiven = BigDecimal.ZERO;
		BigDecimal inviteGiven = BigDecimal.ZERO;
		BigDecimal accumulatedProfit = BigDecimal.ZERO;

		try {
			List<StatisticUserBillAmountReponseDTO> receivedStatistic = receivedStatisticFuture.get();
			log.info("myInvestAmountStatistics userId={}, receivedStatistic:{}", userId, JSON.toJSON(receivedStatistic));

			for (StatisticUserBillAmountReponseDTO statisticUserBillAmountReponseDTO: receivedStatistic) {
				if(statisticUserBillAmountReponseDTO != null) {
					if(BillAmountStatisticsEnum.RECEIVED_PAYMENT_INTEREST.equals(statisticUserBillAmountReponseDTO.getBillAmountStatisticsEnum())){
						investIncome = statisticUserBillAmountReponseDTO.getAmount() == null ? BigDecimal.ZERO : statisticUserBillAmountReponseDTO.getAmount();
					}
					if(BillAmountStatisticsEnum.PLATFORM_PRIZE.equals(statisticUserBillAmountReponseDTO.getBillAmountStatisticsEnum())){
						platformGiven = statisticUserBillAmountReponseDTO.getAmount() == null ? BigDecimal.ZERO : statisticUserBillAmountReponseDTO.getAmount();
					}

					if(BillAmountStatisticsEnum.CARD_AND_REDPACKET.equals(statisticUserBillAmountReponseDTO.getBillAmountStatisticsEnum())){
						prize = statisticUserBillAmountReponseDTO.getAmount() == null ? BigDecimal.ZERO : statisticUserBillAmountReponseDTO.getAmount();

					}
					if(BillAmountStatisticsEnum.RECOMMEND_PRIZE.equals(statisticUserBillAmountReponseDTO.getBillAmountStatisticsEnum())){
						inviteGiven = statisticUserBillAmountReponseDTO.getAmount() == null ? BigDecimal.ZERO : statisticUserBillAmountReponseDTO.getAmount();
					}
					if(BillAmountStatisticsEnum.ACCUMULATED_PROFIT.equals(statisticUserBillAmountReponseDTO.getBillAmountStatisticsEnum())){
						accumulatedProfit = statisticUserBillAmountReponseDTO.getAmount() == null ? BigDecimal.ZERO : statisticUserBillAmountReponseDTO.getAmount();
					}
				}
			}
		} catch (Exception e) {
			log.error("远程调用服务失败InterruptedException:", e);
		}

		responseVO.setInvestIncome(investIncome);
		responseVO.setPrize(prize);
		// 平台奖励：平台发放的平台加息、活动加息、活动现金奖励、活动补帖等。（原尽调或担保收益已合并到平台奖励中）
		responseVO.setPlatformGiven(platformGiven);
		responseVO.setInviteGiven(inviteGiven);

		responseVO.setIncomeTotal(accumulatedProfit);

		return Result.with(responseVO);
	}
}
